import jwt
import datetime
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)

# 允许来自 Vue 项目的跨域请求
CORS(app, resources={r"/api/*": {"origins": "http://localhost:8081"}})

# ───────────── 配置 ─────────────
SECRET_KEY = "xujiahoi.monitored_monitored_monitored_monitored_monitored"
EXPIRATION = datetime.timedelta(hours=1)

# 模拟用户数据库（用户名+密码）
users_db = {
    "username": "admin",
    "password": "123456"
}

# 食物数据
foods = [
    {
        "foodName": "沙拉碗",
        "foodPrice": 25,
        "foodImage": "food1.png",
        "foodDescription": "新鲜制作的沙拉碗，选用当季蔬菜与优质生菜搭配，富含膳食纤维和多种维生素。低脂酱料让口感更清爽，是健康饮食的首选。",
        "stock": 1
    },
    {
        "foodName": "杂粮碗",
        "foodPrice": 22,
        "foodImage": "food2.png",
        "foodDescription": "杂粮碗由五种精选粗粮精心熬制而成，富含丰富的碳水化合物和微量元素，有助于增强饱腹感，适合健身人士和追求健康的你。",
        "stock": 80
    },
    {
        "foodName": "酸奶碗",
        "foodPrice": 18,
        "foodImage": "food3.png",
        "foodDescription": "酸奶碗采用天然发酵酸奶，搭配少量蜂蜜和坚果，口感醇厚，富含益生菌，帮助调节肠道菌群，提升消化能力。",
        "stock": 120
    },
    {
        "foodName": "时令果汁",
        "foodPrice": 15,
        "foodImage": "food4.png",
        "foodDescription": "时令果汁选用当季水果鲜榨而成，无添加糖分，保留水果原汁原味，营养丰富，是补充维生素的理想选择。",
        "stock": 150
    }
]

# 登录接口
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get("username")
    password = data.get("password")

    if username == users_db["username"] and password == users_db["password"]:
        payload = {
            "username": username,
            "exp": datetime.datetime.utcnow() + EXPIRATION
        }
        token = jwt.encode(payload, SECRET_KEY, algorithm="HS256")
        return jsonify({
            "code": 200,
            "data": [{
                "username": username,
                "token": token
            }],
            "message": "登录成功"
        })
    else:
        return jsonify({
            "code": 400,
            "data": [{}],
            "message": "登录失败"
        })

# 获取食物列表接口
@app.route('/api/foods', methods=['GET'])
def get_foods():
    return jsonify({
        "code": 200,
        "data": foods,
        "message": "获取食物成功"
    })

# 启动应用
if __name__ == '__main__':
    app.run(debug=True, port=5000)
